package com.manus;

import com.accurev.common.data.IssueData;
import com.accurev.common.process.AccuWorkProcess;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * This class processes the isues on the stream. It will look for the
 * requirements for the promote in terms of the state of the issue
 */
public class Issues {

    public static String ISSUE_FIELD_FOR_STATE = "State";
    public static Integer DEPENDENCY_RELATIONSHIP = 1;
    private AccuWorkProcess accuWorkProcess;

    public void setAccuWorkProcess(AccuWorkProcess accuWorkProcess) {
        this.accuWorkProcess = accuWorkProcess;
    }

    public List<String> processStreamIssues(String depot, String user, List<String> streamIssues) {
        if (accuWorkProcess == null){
            accuWorkProcess = new AccuWorkProcess();
        }

        Map<String, IssueData> issueDetails = accuWorkProcess.getIssuesDetails(depot, user, streamIssues);

        return getIssuesThatAreApproved(issueDetails);
    }

    private List<String> getIssuesThatAreApproved(Map<String, IssueData> issueDetails) {
        List<String> approvedIssues = new ArrayList<String>();

        for (IssueData issueData : issueDetails.values()) {
            String issueState = issueData.getFieldValue(ISSUE_FIELD_FOR_STATE);
            if (issueState.contains("Approved")) {
                approvedIssues.add(issueData.getIssueNumber());
            }
        }

        return approvedIssues;
    }

    public void determineIssueDependencies(String depot, List<String> approvedIssues) throws Exception {
        if (accuWorkProcess == null){
            accuWorkProcess = new AccuWorkProcess();
        }

        for (String issueNum : approvedIssues) {
            List<Integer> relationships = accuWorkProcess.getIssueRelationships(depot, issueNum, 2);
            if (relationships.contains(DEPENDENCY_RELATIONSHIP)){
                throw new Exception("Issue has a dependency");
            }
        }
    }
}
